import ConfigManager from './ConfigManager.js';
import ServiceRegistry from './ServiceRegistry.js';
import { LifeserviceConfig, ServiceOptions } from '../types/index.js';

// LifeService框架核心服务类
class LifeserviceCore {
  constructor(options = {}) {
    // 初始化配置管理器
    this.configManager = new ConfigManager({
      ...LifeserviceConfig,
      ...options
    });

    // 初始化服务注册器
    this.serviceRegistry = new ServiceRegistry();

    // 服务实例缓存
    this.instances = new Map();
    this.booted = false;
    this.bootOrder = [];
  }

  // 获取配置管理器
  get config() {
    return this.configManager;
  }

  // 获取服务注册器
  get registry() {
    return this.serviceRegistry;
  }

  // 注册服务
  register(name, service, options = {}) {
    // 合并默认选项
    const mergedOptions = { ...ServiceOptions, ...options };
    
    this.serviceRegistry.register(name, service, mergedOptions);
    return this;
  }

  // 批量注册服务
  registerAll(services) {
    this.serviceRegistry.registerAll(services);
    return this;
  }

  // 获取服务实例
  get(name) {
    const serviceConfig = this.serviceRegistry.getServiceConfig(name);
    
    if (!serviceConfig) {
      throw new Error(`Service ${name} is not registered`);
    }

    // 如果实例已存在，直接返回
    if (this.instances.has(serviceConfig.name)) {
      return this.instances.get(serviceConfig.name);
    }

    // 创建新实例
    const { service, options } = serviceConfig;
    let instance;

    // 处理不同类型的服务注册方式
    if (typeof service === 'function') {
      instance = new service(this);
    } else {
      instance = service;
    }

    // 存储实例
    this.instances.set(serviceConfig.name, instance);

    // 如果框架已启动，且服务有boot方法，调用它
    if (this.booted && instance.boot && typeof instance.boot === 'function') {
      instance.boot(options);
    }

    return instance;
  }

  // 获取配置值
  getConfig(key, defaultValue = undefined) {
    return this.configManager.get(key, defaultValue);
  }

  // 设置配置值
  setConfig(key, value) {
    this.configManager.set(key, value);
    return this;
  }

  // 注册服务别名
  alias(alias, serviceName) {
    this.serviceRegistry.alias(alias, serviceName);
    return this;
  }

  // 启动所有服务
  boot() {
    if (this.booted) {
      console.warn('LifeService is already booted');
      return this;
    }

    // 获取所有服务
    const serviceNames = this.serviceRegistry.getServiceNames();
    
    // 根据优先级排序服务
    const sortedServices = this.sortServicesByPriority(serviceNames);
    
    // 为每个服务创建实例并调用boot方法
    for (const name of sortedServices) {
      try {
        const instance = this.get(name);
        const serviceConfig = this.serviceRegistry.getServiceConfig(name);
        
        if (instance.boot && typeof instance.boot === 'function') {
          instance.boot(serviceConfig.options);
        }
        
        this.bootOrder.push(name);
      } catch (error) {
        console.error(`Failed to boot service ${name}:`, error);
        // 根据配置决定是否继续启动其他服务
        if (this.configManager.get('stopOnError', false)) {
          throw error;
        }
      }
    }

    this.booted = true;
    console.log('LifeService booted successfully with services:', this.bootOrder);
    return this;
  }

  // 关闭所有服务（按启动顺序的反向关闭）
  shutdown() {
    if (!this.booted) {
      console.warn('LifeService is not booted');
      return this;
    }

    // 反向启动顺序关闭服务
    const shutdownOrder = [...this.bootOrder].reverse();
    
    for (const name of shutdownOrder) {
      try {
        const instance = this.instances.get(name);
        if (instance && instance.shutdown && typeof instance.shutdown === 'function') {
          instance.shutdown();
        }
      } catch (error) {
        console.error(`Failed to shutdown service ${name}:`, error);
      }
    }

    // 清空实例缓存
    this.instances.clear();
    this.bootOrder = [];
    this.booted = false;
    console.log('LifeService shutdown successfully');
    return this;
  }

  // 检查服务是否已注册
  has(name) {
    return this.serviceRegistry.has(name);
  }

  // 获取所有服务名称
  getServiceNames() {
    return this.serviceRegistry.getServiceNames();
  }

  // 根据优先级排序服务
  sortServicesByPriority(serviceNames) {
    const servicesWithPriority = serviceNames.map(name => {
      const config = this.serviceRegistry.getServiceConfig(name);
      return {
        name,
        priority: config?.options?.priority || 0,
        dependencies: config?.options?.dependencies || []
      };
    });

    // 拓扑排序算法处理依赖关系
    const sorted = [];
    const visited = new Set();
    const tempVisited = new Set();
    
    const visit = (service) => {
      if (tempVisited.has(service.name)) {
        throw new Error(`Circular dependency detected for service: ${service.name}`);
      }
      
      if (!visited.has(service.name)) {
        tempVisited.add(service.name);
        
        // 先访问依赖的服务
        for (const dep of service.dependencies) {
          const depService = servicesWithPriority.find(s => s.name === dep || 
            this.serviceRegistry.getServiceConfig(dep)?.name === dep);
          if (depService) {
            visit(depService);
          }
        }
        
        tempVisited.delete(service.name);
        visited.add(service.name);
        sorted.push(service.name);
      }
    };
    
    // 按优先级降序排序，优先级高的先启动
    servicesWithPriority.sort((a, b) => b.priority - a.priority);
    
    // 执行拓扑排序
    for (const service of servicesWithPriority) {
      if (!visited.has(service.name)) {
        visit(service);
      }
    }
    
    return sorted;
  }

  // 获取服务组中的所有实例
  getServicesByGroup(group) {
    const serviceNames = this.serviceRegistry.getGroupServices(group);
    return serviceNames.map(name => this.get(name));
  }

  // 重新加载服务（用于开发环境）
  reloadService(name) {
    if (!this.has(name)) {
      throw new Error(`Service ${name} is not registered`);
    }

    // 关闭现有实例
    const instance = this.instances.get(name);
    if (instance && instance.shutdown && typeof instance.shutdown === 'function') {
      instance.shutdown();
    }

    // 清除实例缓存
    this.instances.delete(name);

    // 重新创建实例
    const newInstance = this.get(name);
    console.log(`Service ${name} reloaded`);
    
    return newInstance;
  }
}

export default LifeserviceCore;